<!--
  * 司机回库单
  *
-->
<template>
  <!---------- 查询表单form begin ----------->
  <a-card size="small" :bordered="false" :hoverable="false" class="query-form-wrapper smart-margin-bottom10 smart-radius-2">
    <a-form :model="queryForm" labelAlign="left">
      <a-row :gutter="[8, 10]">
        <a-col :span="{ sm: 7, md: 6 }">
          <a-form-item label="单据日期" class="smart-margin-bottom0">
            <custom-range-picker v-model:value="queryForm.create_time" />
          </a-form-item>
        </a-col>
        <a-col :span="4">
          <a-form-item label="司机" class="smart-margin-bottom0">
            <Select name="Driver" v-model:value="queryForm.driver_id" placeholder="司机" @input-enter="onSearch" />
          </a-form-item>
        </a-col>
        <a-col :span="4">
          <a-form-item label="出库仓库" name="out_warehouse_id" class="smart-margin-bottom0">
            <Select name="Warehouse" v-model:value="queryForm.out_warehouse_id" :fetch-params="outWarehouse.warehouse" placeholder="请选择仓库" @input-enter="onSearch" />
          </a-form-item>
        </a-col>
        <a-col :span="4">
          <a-form-item label="回库仓库" name="return_warehouse_id" class="smart-margin-bottom0">
            <Select name="Warehouse" v-model:value="queryForm.return_warehouse_id" :fetch-params="selectFetchParams.warehouse" placeholder="请选择仓库" @input-enter="onSearch" />
          </a-form-item>
        </a-col>
        <a-col :span="4">
          <a-button-group>
            <a-button type="primary" html-type="submit" @click="onSearch">
              <template #icon>
                <SearchOutlined />
              </template>
              查询
            </a-button>
            <a-button @click="resetQuery">
              <template #icon>
                <ReloadOutlined />
              </template>
              重置
            </a-button>
            <SearchFormCollapse v-model="expand" />
          </a-button-group>
        </a-col>
        <template v-if="expand">
          <a-col :span="4">
            <a-form-item label="回库类型" class="smart-margin-bottom0">
              <EnumSelect enum-name="RETURNWAREHOUSE_TYPE_ENUM" v-model:value="queryForm.return_type" placeholder="回库类型" @submit="onSearch" />
            </a-form-item>
          </a-col>
          <a-col :span="4">
            <a-form-item label="回库状态" class="smart-margin-bottom0">
              <EnumSelect enum-name="RETURNWAREHOUSE_STATUS_ENUM" v-model:value="queryForm.return_status" placeholder="回库状态" @submit="onSearch" />
            </a-form-item>
          </a-col>
          <a-col :span="4">
            <a-form-item label="回库单号" class="smart-margin-bottom0">
              <a-input v-model:value.trim="queryForm.return_no" placeholder="单据编号" allow-clear />
            </a-form-item>
          </a-col>
        </template>
      </a-row>
    </a-form>
  </a-card>
  <!---------- 查询表单form end ----------->

  <a-card size="small" :bordered="false" :hoverable="true" class="query-table-wrapper">
    <!---------- 表格操作行 begin ----------->
    <a-row class="smart-table-btn-block">
      <div class="smart-table-operate-block">
        <a-button @click="onExport" type="primary" v-privilege="'return:warehouse:export'">
          <template #icon>
            <ExportOutlined />
          </template>
          导出
        </a-button>
      </div>
      <div class="smart-table-setting-block">
        <TableOperator v-model="columns" :tableId="TABLE_ID_CONST.BUSINESS.ERP.GOODS" :refresh="queryData" />
      </div>
    </a-row>
    <!---------- 表格操作行 end ----------->
    <div class="table-wrapper">
      <a-table size="small" :dataSource="tableData" :columns="columns" rowKey="id" bordered :scroll="{ x: 'max-content', y: tableScrollY }" :pagination="false" :showSorterTooltip="false" :loading="tableLoading" :row-selection="{}">
        <template #bodyCell="{ text, record, column }">
          <template v-if="column.dataIndex === 'return_no'">
            <CopyText :text="text">
              <a @click="detail(record)">{{ text }}</a>
            </CopyText>
          </template>
          <template v-if="column.dataIndex === 'return_type'">
            <a-tag :color="TagColor[text]">{{ getDescByValue('RETURNWAREHOUSE_TYPE_ENUM', Number(text)) }}</a-tag>
          </template>
          <template v-if="column.dataIndex === 'return_status'">
            <a-tag :color="TagColor[text]">{{ getDescByValue('RETURNWAREHOUSE_STATUS_ENUM', Number(text)) }}</a-tag>
          </template>
          <template v-if="column.dataIndex === 'sign'">
            <span>{{ record?.sign_large_qty }}整{{ record?.sign_middle_qty }}中{{ record?.sign_small_qty }}散</span>
          </template>
          <template v-if="column.dataIndex === 'driverWarehouse'">
            <span
              >{{ record.driverWarehouse?.name }}<span v-if="record.driverWarehouse?.attribute_type">({{ getDescByValue('WAREHOUSE_ATTRIBUTE_TYPE', record.driverWarehouse?.attribute_type) }})</span>
            </span>
          </template>
          <template v-if="column.dataIndex === 'intoWarehouse'">
            <span
              >{{ record.intoWarehouse?.name }}<span v-if="record.intoWarehouse?.attribute_type">({{ getDescByValue('WAREHOUSE_ATTRIBUTE_TYPE', record.intoWarehouse?.attribute_type) }})</span>
            </span>
          </template>
          <template v-if="column.dataIndex === 'action'">
            <div class="smart-table-operate">
              <a-button @click="detail(record)" type="link" style="color: #97999c" v-if="record.return_status !== 1">详情</a-button>
              <a-button @click="print(record)" type="link">打印</a-button>
              <!-- <template v-if="record.return_status == 1">
                <a-button @click="sign(record)" type="link" v-privilege="'return:warehouse:check'">签收</a-button>
              </template> -->
            </div>
          </template>
        </template>
        <template #summary>
          <a-table-summary fixed>
            <a-table-summary-row>
              <a-table-summary-cell>总计</a-table-summary-cell>
              <a-table-summary-cell />
              <a-table-summary-cell />
              <a-table-summary-cell />
              <a-table-summary-cell />
              <a-table-summary-cell />
              <a-table-summary-cell />
              <a-table-summary-cell>
                <a-typography-text type="danger">{{ total_amount.total_order_count || 0 }}</a-typography-text>
              </a-table-summary-cell>
              <a-table-summary-cell>
                <a-typography-text type="danger">{{ total_amount.total_order_amount || 0 }}</a-typography-text>
              </a-table-summary-cell>
              <a-table-summary-cell>
                <a-typography-text type="danger">{{ total_amount.total_sign_num || 0 }}</a-typography-text>
              </a-table-summary-cell>
              <a-table-summary-cell>
                <a-typography-text type="danger">{{ total_amount.total_sign_amount || 0 }}</a-typography-text>
              </a-table-summary-cell>
              <a-table-summary-cell />
              <a-table-summary-cell />
              <a-table-summary-cell />
              <a-table-summary-cell />
            </a-table-summary-row>
          </a-table-summary>
        </template>
      </a-table>
    </div>
    <div class="smart-query-table-page query-table-page">
      <a-pagination showSizeChanger showQuickJumper show-less-items :pageSizeOptions="PAGE_SIZE_OPTIONS" :defaultPageSize="queryForm.limit" v-model:current="queryForm.page" v-model:pageSize="queryForm.limit" :total="total" @change="queryData" @showSizeChange="queryData" :show-total="(total) => `共${total}条`" />
    </div>
    <!---------- 签收 begin ----------->
    <PurchaseSignDetailsModal ref="signRef" @reload-list="queryData" />
    <!---------- 签收 end ----------->
    <!---------- 详情 begin ----------->
    <PurchaseReceiptDetailsModal ref="detailRef" @reload-list="queryData" />
    <!---------- 详情 end ----------->
    <PurchaseReceiptPrintModal ref="printRef" />
  </a-card>
</template>
<script setup lang="ts">
import CustomRangePicker from '@/components/business/custom-range-picker/index.vue'
import PurchaseSignDetailsModal from './components/return-sign-details-modal.vue'
import PurchaseReceiptDetailsModal from './components/return-receipt-details-modal.vue'
import PurchaseReceiptPrintModal from './components/return-receipt-print-modal.vue'
import { driverReturnOrderApi } from '@/api/business/storage/returnwarehouse-api'
import { PAGE_SIZE_OPTIONS, DEFAULT_TIME_RANGE } from '@/constants/system/common-const'
import Select from '@/components/business/select/index.vue'
import TableOperator from '@/components/support/table-operator/index.vue'
import SearchFormCollapse from '@/components/support/search-form-collapse/index.vue'
import { TABLE_ID_CONST } from '@/constants/support/table-id-const'
import EnumSelect from '@/components/framework/enum-select/index.vue'
import _ from 'lodash'
import { message, Modal } from 'ant-design-vue'
import { errorSentry } from '@/lib/error-sentry'
import { useQuery } from '@/hooks/web/use-query-hook'
import { QUERY_FORM_OP } from '@/constants/support/query-form-op-const'
import { useEnums } from '@/hooks/plugins/useEnums'
import { useAppConfigStore } from '@/store/modules/app-store'
import { useUserStore } from '@/store/modules/user-store'
import { useResize } from '@/hooks/web/use-resize-hook'
import { useLoadingStore } from '@/store/modules/loading-store'
import { WAREHOUSE_TYPE, WAREHOUSE_ATTRIBUTE_TYPE } from '@/constants/business/storage/warehouse/warehouse-const'
import { IN_STRATEGY } from '@/constants/business/storage/process-rules/process-rules-const'
import { useRoute } from 'vue-router'
import { ref, onMounted } from 'vue'

const route = useRoute()
const appConfigStore = useAppConfigStore()
const userStore = useUserStore()
const loadingStore = useLoadingStore()
const { getDescByValue } = useEnums()
// ----------------------------- tag入库状态 -----------------------------
enum TagColor {
  'blue' = 1,
  'green',
  'orange',
  'red'
}
// ----------------------------- 计算表格高度 -----------------------------
const { tableScrollY, expand } = useResize()

// ---------------------------- 表格列 ----------------------------

const columns = computed(() => [
  {
    title: '回库单号',
    dataIndex: 'return_no',
    width: appConfigStore.$state.compactFlag ? 150 : 180
  },
  {
    title: '司机',
    dataIndex: ['driver', 'name']
  },
  {
    title: '出库仓库',
    dataIndex: 'driverWarehouse'
  },
  {
    title: '回库仓库',
    dataIndex: 'intoWarehouse'
  },
  {
    title: '回库类型',
    dataIndex: 'return_type'
  },
  {
    title: '回库状态',
    dataIndex: 'return_status',
    width: 60
  },
  {
    title: '订单数量',
    dataIndex: 'order_count',
    width: 100
  },
  {
    title: '订单金额',
    dataIndex: 'order_amount',
    width: 100
  },
  {
    title: '签收数量',
    dataIndex: 'sign',
    width: 100
  },
  {
    title: '签收金额',
    dataIndex: 'sign_amount',
    width: 100
  },
  {
    title: '单据时间',
    dataIndex: 'create_time'
  },
  {
    title: '签收时间',
    dataIndex: 'sign_time'
  },
  {
    title: '签收备注',
    dataIndex: 'sign_remark'
  },

  {
    title: '操作',
    dataIndex: 'action',
    fixed: 'right',
    width: appConfigStore.$state.compactFlag ? 120 : 140
  }
])

// ---------------------------- 查询数据表单和方法 ----------------------------
interface TotalAmount {
  total_order_amount: number
  total_sign_amount: number
  total_order_count: number
  total_sign_num: number
}

const total_amount = ref<TotalAmount>({
  total_order_amount: 0,
  total_sign_amount: 0,
  total_order_count: 0,
  total_sign_num: 0
})
const warehouse = ref('')
const { queryForm, queryFormOp, tableData, tableLoading, total, resetQuery, onSearch, queryData } = useQuery({
  fetchDataApi: async (params) => {
    const res: any = await driverReturnOrderApi.queryDriverReturnOrderList(params)
    const { val, ...other } = res.data
    total_amount.value = _.pick(other, Object.keys(total_amount.value)) as TotalAmount
    return {
      list: res.data.data,
      total: res.data.total
    }
  },
  queryFormFilter: {
    return_no: '',
    create_time: DEFAULT_TIME_RANGE.value,
    return_type: null,
    return_status: null,
    driver_id: null,
    return_warehouse_id: null
  },
  queryFormOp: {
    return_no: QUERY_FORM_OP['模糊查询'],
    create_time: QUERY_FORM_OP['范围查询'],
    return_type: QUERY_FORM_OP['全等查询'],
    return_status: QUERY_FORM_OP['全等查询'],
    driver_id: QUERY_FORM_OP['全等查询'],
    return_warehouse_id: QUERY_FORM_OP['全等查询']
  }
})

onActivated(() => {
  queryData()
})

onMounted(() => {
  queryForm.value.return_no = route.query?.return_no
  queryForm.value.create_time = route.query.create_time || DEFAULT_TIME_RANGE.value
})

// Select查询参数
const selectFetchParams = {
  warehouse: {
    filter: {
      warehouse_type: WAREHOUSE_TYPE.FIXED.value,
      attribute_type: [WAREHOUSE_ATTRIBUTE_TYPE.WAREHOUSE.value, WAREHOUSE_ATTRIBUTE_TYPE.TEMPORARY.value, WAREHOUSE_ATTRIBUTE_TYPE.EXPIRED.value]
    },
    op: {
      warehouse_type: QUERY_FORM_OP['全等查询'],
      attribute_type: QUERY_FORM_OP['IN查询']
    },
    fields: 'id,name'
  }
}
const outWarehouse = computed(() => {
  return {
    warehouse: {
      filter: {
        warehouse_type: WAREHOUSE_TYPE.MOVE.value,
        accountable_type: 2,
        attribute_type: [WAREHOUSE_ATTRIBUTE_TYPE.WAREHOUSE.value, WAREHOUSE_ATTRIBUTE_TYPE.TEMPORARY.value, WAREHOUSE_ATTRIBUTE_TYPE.EXPIRED.value]
      },
      op: {
        warehouse_type: QUERY_FORM_OP['全等查询'],
        attribute_type: QUERY_FORM_OP['IN查询']
      },
      fields: 'id,name',
      driver_id: queryForm.value.driver_id
    }
  }
})

// ---------------------------- 签收 ----------------------------
const signRef = ref()

const sign = (goodsData) => {
  signRef.value.showDrawer(goodsData)
}
// ---------------------------- 详情 ----------------------------
const detailRef = ref()

const detail = (goodsData) => {
  detailRef.value.showDrawer(goodsData)
}

// ---------------------------- 打印 ----------------------------
const printRef = ref()

const print = async (goodsData) => {
  printRef.value.showDrawer(goodsData)
}

// ------------------------------- 导出和导入 ---------------------------------
// 导出
function onExport() {
  const { page, limit, ...filter } = queryForm.value
  const data = {
    filter: JSON.stringify(filter),
    op: JSON.stringify(queryFormOp)
  }
  driverReturnOrderApi.exportXlsx(data)
}
</script>
